package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 使用springboot提供的多线程的分装工具@Async，相当于创建一个新的线程来执行
     */
    @Async
    public void saveTimeLine(Long userId, ObjectId movementId) {
        //模拟5秒发布
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        //后续版本中，可以在这里排除不可见的好友
        //3.一个好友，构建一个时间线表数据
        for (Friend friend : list) {
            MovementTimeLine line = new MovementTimeLine();
            line.setMovementId(movementId);
            line.setUserId(userId);
            line.setFriendId(friend.getFriendId());
            line.setCreated(System.currentTimeMillis());
            mongoTemplate.save(line);
        }
    }
}
